package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.HuaWeiIoTService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备Service业务层处理
 *
 * @author FuJiaWei
 * @date 2025-05-30
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private HuaWeiIoTService huaWeiIoTService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        List<ProductSummary> productSummaries = huaWeiIoTService.selectProduceList();
        List<ProductVo> productVoList = productSummaries.stream().map(p -> new ProductVo(p.getProductId(), p.getName())).collect(Collectors.toList());
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, productVoList);
    }

    /**
     * 查询所有产品列表
     */
    @Override
    public List<ProductVo> findAll() {
        List<ProductVo> productVos = (List<ProductVo>) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        return productVos;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //1、设备名称不能重复
        Long count = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count > 0) {
            throw new ServiceException("设备名称已存在，请重新输入");
        }
        //设备表示码不能重复
        count = lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if (count > 0) {
            throw new ServiceException("设备标识码已存在，请重新输入");
        }
        //判断同一位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if (count > 0) {
            throw new ServiceException("该位置或老人已经绑定过同一类产品设备了！");
        }
        //注册设备
        AddDeviceResponse response = huaWeiIoTService.addDevice(dto);
        //获取IotId
        String deviceId = response.getDeviceId();
        //获取secret
        String secret = response.getAuthInfo().getSecret();
        //保存到数据库
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(secret);
        save(device);
    }

    /**
     * 查询设备详细数据
     *
     * @param iotId
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库设备数据
        Device deviceInDb = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (null == deviceInDb) {
            throw new ServiceException("设备不存在");
        }
        //拷贝DeviceVo
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(deviceInDb, DeviceDetailVo.class);
        //查询IOT平台设备数据
        ShowDeviceResponse response = huaWeiIoTService.selectDeviceByIotId(iotId);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    // 转时区,获取系统中的时区
                    .withZoneSameInstant(ZoneId.systemDefault())
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     */
    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        List<DeviceShadowDataVo> voList = new ArrayList<>();
        //查询设备影子数据
        ShowDeviceShadowResponse response = huaWeiIoTService.queryServiceProperties(iotId);
        List<DeviceShadowData> shadow = response.getShadow();
        shadow.forEach(dsData -> {
            DeviceShadowProperties reported = dsData.getReported();
            String eventTime = reported.getEventTime();
            LocalDateTime parse = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换, 当前所在的时区
            LocalDateTime activeDateTime = parse.atZone(ZoneId.from(ZoneOffset.UTC))
                    // 转时区,获取系统中的时区
                    .withZoneSameInstant(ZoneId.systemDefault())
                    .toLocalDateTime();
            LinkedHashMap<String, Object> propertiesData = (LinkedHashMap) reported.getProperties();
            propertiesData.forEach((key, value) -> {
                DeviceShadowDataVo deviceShadowDataVo = new DeviceShadowDataVo();
                deviceShadowDataVo.setFunctionId(key);
                deviceShadowDataVo.setValue(value.toString());
                deviceShadowDataVo.setEventTime(activeDateTime);
                voList.add(deviceShadowDataVo);
            });
        });
        return voList;
    }

    /**
     * 修改设备
     *
     * @param dto
     */
    @Override
    public void updateDeviceByIotId(DeviceDto dto) {
        Long bindingLocation = dto.getBindingLocation();
        if (null == bindingLocation) {
            throw new ServiceException("设备绑定位置不能为空");
        }
        huaWeiIoTService.updateDeviceByIotId(dto);
        Device device = BeanUtil.toBean(dto, Device.class);
        Integer locationType = device.getLocationType();
        LambdaUpdateWrapper<Device> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Device::getId, device.getId());
        if (locationType == 0) {
            updateWrapper.set(Device::getPhysicalLocationType, null);
        }
        update(device, updateWrapper);
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        huaWeiIoTService.deleteDeviceByIotId(iotId);
        lambdaUpdate().eq(Device::getIotId, iotId).remove();
    }
}
